package com.bwc.codevideo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class TargetActivity : AppCompatActivity() {
    private var et_target_distance : EditText?= null
    private var et_target_speed : EditText?= null
    private var et_target_heart : EditText?= null
    private var et_target_calorie : EditText?= null
    private var et_target_frequency : EditText?= null
    private var et_input : EditText ?= null


    private var target_distance : String ?= null
    private var target_speed : String ?= null
    private var target_heart : String ?= null
    private var target_calorie : String ?= null
    private var target_frequency : String ?= null
    private var input : String ?= null
    private var btn_send_ai : Button?= null
    private var tv_output_ai : TextView?= null

    private var target = false
    private var running = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_target)
        et_target_distance = findViewById(R.id.et_target_distance)
        et_target_speed = findViewById(R.id.et_target_speed)
        et_target_heart = findViewById(R.id.et_target_heart)
        et_target_calorie = findViewById(R.id.et_target_calorie)
        et_target_frequency = findViewById(R.id.et_target_frequency)
        et_input = findViewById(R.id.et_input)
        btn_send_ai = findViewById(R.id.btn_send_ai)
        tv_output_ai = findViewById(R.id.tv_output_ai)

        onTextChange()
        sendAi()
    }

    private fun onTextChange() {
        et_target_distance?.addTextChangedListener { text ->
            Log.d("TargetActivity---", "et_target_distance: $text")
            target_distance = text.toString()
            checkTargetState()
        }
        et_target_speed?.addTextChangedListener { text ->
            Log.d("TargetActivity---", "et_target_speed: $text")
            target_speed = text.toString()
            checkTargetState()
        }
        et_target_heart?.addTextChangedListener { text ->
            Log.d("TargetActivity---", "et_target_heart: $text")
            target_heart = text.toString()
            checkTargetState()
        }
        et_target_frequency?.addTextChangedListener { text ->
            Log.d("TargetActivity---", "et_target_frequency: $text")
            target_frequency = text.toString()
            checkTargetState()
        }
        et_target_calorie?.addTextChangedListener { text ->
            Log.d("TargetActivity---", "et_target_calorie: $text")
            target_calorie = text.toString()
            checkTargetState()
        }
        et_input?.addTextChangedListener { text ->
            Log.d("TargetActivity---", "et_input: ${text?.length}")
            input = text.toString()
            checkTargetState()
        }
    }


    private fun sendAi() {
        btn_send_ai?.setOnClickListener {
            if (target_distance != null
                || target_speed != null
                || target_heart != null
                || target_calorie != null
                || target_frequency != null
                || input != null){

                val logging = HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                }

                val okHttpClient = OkHttpClient.Builder()
                    .addInterceptor(logging)
                    .build()

                val retrofit = Retrofit.Builder()
                    .baseUrl("https://api.coze.cn/v1/")
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()

                val cozeApi = retrofit.create(CozeApi::class.java)
                val parameters = buildParametersSkippingNulls{
                    this["target"] = target
                    this["running"] = running
                    this["targetHeart"] = target_heart
                    this["targetDistance"] = target_distance
                    this["targetSpeed"] = target_speed
                    this["targetCalorie"] = target_calorie
                    this["targetFrequency"] = target_frequency
                    this["input"] = input
                }

                val request = CozeRequest(
                    workflowId = "7520151127414210600",
                    parameters = parameters
                )
                val call = cozeApi.runWorkflow(request, "Bearer pat_JG7C6fIyVcpyDjgnyo9w29Y8YX3a1NXX9Rc7lHffka1mSkeowPbk48jvGRJOSS2r")
                call.enqueue(object : Callback<ResponseBody> {
                    override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                        if (response.isSuccessful) {
                            val responseBody = response.body()?.string()

                            val responseJson = JSONObject(responseBody) // 第一步解析外层 JSON
                            val nestedData = responseJson.getString("data") // 这是嵌套的 JSON 字符串
                            val innerJson = JSONObject(nestedData) // 第二步解析内层 JSON
                            val result = innerJson.getString("data") // 最终拿到你要的内容
                            Log.d("TargetActivity---", result)
                            tv_output_ai?.text = "请求的结果显示在这里：$result"
                            Log.d("TargetActivity---", "成功: $responseBody")
                        } else {
                            Log.e("TargetActivity---", "错误码: ${response.code()}")
                        }
                    }

                    override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                        Log.e("TargetActivity---", "网络失败: ${t.message}")
                    }
                })

            }else{
                Toast.makeText(this,"当前数据不能为空", Toast.LENGTH_SHORT).show()
            }
        }
    }


    private fun buildParametersSkippingNulls(
        block: MutableMap<String, Any?>.() -> Unit
    ): Map<String, Any> {
        val tempMap = mutableMapOf<String, Any?>()
        tempMap.block()
        return tempMap.filterValues { it != null } as Map<String, Any>
    }

    private fun checkTargetState() {
        Log.d("TargetActivity---", "检查 target 状态：")
        Log.d("TargetActivity---", "target_distance: $target_distance")
        Log.d("TargetActivity---", "target_speed: $target_speed")
        Log.d("TargetActivity---", "target_heart: $target_heart")
        Log.d("TargetActivity---", "target_frequency: $target_frequency")
        Log.d("TargetActivity---", "target_calorie: $target_calorie")
        Log.d("TargetActivity---", "input: $input")

        val allBlank = listOf(
            target_distance,
            target_speed,
            target_heart,
            target_frequency,
            target_calorie,
            input
        ).all { it.isNullOrBlank() }

        target = !allBlank

        Log.d("TargetActivity---", "target 状态: $target")
    }
}